package cn.dansj.handler.tasks;

import cn.dansj.annotation.MarkAsTask;
import cn.dansj.annotation.TaskParam;
import cn.dansj.common.utils.json.DictMap;
import cn.dansj.common.request.RestTemplateUtils;
import cn.dansj.common.utils.transfer.StringUtils;
import cn.dansj.common.utils.transfer.Transformation;
import cn.dansj.common.utils.transfer.Verification;
import cn.dansj.utils.calendar.SimpleCalendar;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xxl.job.handler.Job;

import java.util.ArrayList;
import java.util.List;

/**
 * SET @prev_ext = NULL;
 * UPDATE t_calendar_info
 * SET solarTerms = @prev_ext :=if(solarTerms = null or solarTerms = '',if (@prev_ext like '%后',@prev_ext,concat( @prev_ext,'后')), solarTerms)
 * ORDER BY date;
 * <p>
 * type 1 休息日 0 工作日 2 节假日
 */
@SuppressWarnings("all")
@MarkAsTask(id = 3)
public class GetCalendarInfo extends Job {
    @Override
    @TaskParam(name = "year", comment = "年份")
    public void execute() throws Exception {
        final String year = parseParam().getString("year");
        if (Verification.checkNull(year)) logger.warn("年份参数不存在,请检查是否正确传参");
        for (String y : StringUtils.split(year, ",")) {
            if (Transformation.isNumeric(y)) {
                compute(Integer.parseInt(y));
            } else {
                logger.error("param {} parse to int failed", y);
            }
        }
    }

    public void compute(int year) throws Exception {
        logger.info("year:" + year);
        JSONObject jsonObject = RestTemplateUtils.defaultInstance().get("https://www.mxnzp.com/api/holiday/list/year/" + year + "?ignoreHoliday=false&app_id=chretnsinicmefmj&app_secret=BN0fxR6f8buGw5OykrlOiUm6Rv2ywNcF", JSONObject.class);
        String insertSql = "insert into t_calendar_info values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        String delSql = "delete from t_calendar_info where year=?";
        JSONArray data = jsonObject.getJSONArray("data");
        if (data == null) {
            Thread.sleep(1000);
            jsonObject = RestTemplateUtils.defaultInstance().get("https://www.mxnzp.com/api/holiday/list/year/" + year + "?ignoreHoliday=true&app_id=chretnsinicmefmj&app_secret=BN0fxR6f8buGw5OykrlOiUm6Rv2ywNcF", JSONObject.class);
            data = jsonObject.getJSONArray("data");
        }
        List<Object[]> batchArgs = new ArrayList<>();
        for (Object dt : data) {
            JSONArray days = DictMap.parseObject(dt).getJSONArray("days");
            for (Object day : days) {
                JSONObject dayInfo = DictMap.parseObject(day);
                final String date = dayInfo.getString("date");
                String[] dateSplit = StringUtils.split(date, "-");
                String y = dateSplit[0];
                String m = dateSplit[1];
                String d = dateSplit[2];

                final SimpleCalendar.Element calendarDetail = SimpleCalendar.getCalendarDetail(date, "yyyy-MM-dd");

                batchArgs.add(new Object[]{
                        dayInfo.get("date"),
                        dayInfo.get("weekDay"),
                        dayInfo.get("yearTips"),
                        calendarDetail.getcMonth(),
                        calendarDetail.getcDay(),
                        dayInfo.get("type"),
                        dayInfo.get("typeDes"),
                        dayInfo.get("chineseZodiac"),
                        calendarDetail.getSolarTerms(),
                        dayInfo.get("avoid"),
                        dayInfo.get("lunarCalendar"),
                        dayInfo.get("suit"),
                        dayInfo.get("dayOfYear"),
                        dayInfo.get("weekOfYear"),
                        dayInfo.get("constellation"),
                        dayInfo.get("indexWorkDayOfMonth"),
                        y,
                        m,
                        d,
                        calendarDetail.getWeekInMonth(),
                        calendarDetail.getLunarFestival().trim(),
                        calendarDetail.getSolarFestival().trim()
                });
            }
        }
        int update = jdbcTemplate.update(delSql, year);
        logger.info("delete rows:" + update);

        int[] insert = jdbcTemplate.batchUpdate(insertSql, batchArgs);
        logger.info("insert rows:" + insert.length);
    }
}
